package com.lyumall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyumall.common.utils.PageUtils;
import com.lyumall.common.utils.Query;

import com.lyumall.product.dao.CategoryDao;
import com.lyumall.product.entity.CategoryEntity;
import com.lyumall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询菜单
     * @return 菜单列表
     */
    @Override
    public List<CategoryEntity> queryCategory() {

        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        List<CategoryEntity> levelMenus = categoryEntities.stream()
                .filter(item ->
                     item.getParentCid() == 0
                ).map(menu->{
                    menu.setChildCategoryEntity(queryChildCategory(menu, categoryEntities));
                    return menu;
                }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))
                ).collect(Collectors.toList());

        return levelMenus;
    }

    /**
     * 查询子菜单
     * @param root 当前菜单
     * @param all 菜单列表
     * @return 菜单列表
     */
    private List<CategoryEntity> queryChildCategory(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream()
                .filter(item ->
                    item.getParentCid().equals(root.getCatId())
                ).map(menu -> {
                    menu.setChildCategoryEntity(queryChildCategory(menu, all));
                    return menu;
                }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))
                ).collect(Collectors.toList());
        return children;
    }

    /**
     * 逻辑批量删除菜单
     * @param asList 批量id
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、检查当前删除菜单，是否被别的地方引用？
        baseMapper.deleteBatchIds(asList);
    }

}
